home *** CD-ROM | disk | FTP | other *** search
/ Meeting Pearls 2 / Meeting Pearls Vol. II (1995)(GTI - Schatztruhe)[!].iso / Pearls / gfx / pbm / source / jpegV5.lha / jpegV5 / src / jquant1.c < prev    next >
C/C++ Source or Header  |  1994-12-23  |  27KB  |  711 lines

  1. /*
  2.  * jquant1.c
  3.  *
  4.  * Copyright (C) 1991-1994, Thomas G. Lane.
  5.  * This file is part of the Independent JPEG Group's software.
  6.  * For conditions of distribution and use, see the accompanying README file.
  7.  *
  8.  * This file contains 1-pass color quantization (color mapping) routines.
  9.  * These routines provide mapping to a fixed color map using equally spaced
  10.  * color values.  Optional Floyd-Steinberg or ordered dithering is available.
  11.  */
  12.  
  13. #define JPEG_INTERNALS
  14. #include "jinclude.h"
  15. #include "jpeglib.h"
  16.  
  17. #ifdef QUANT_1PASS_SUPPORTED
  18.  
  19.  
  20. /*
  21.  * The main purpose of 1-pass quantization is to provide a fast, if not very
  22.  * high quality, colormapped output capability.  A 2-pass quantizer usually
  23.  * gives better visual quality; however, for quantized grayscale output this
  24.  * quantizer is perfectly adequate.  Dithering is highly recommended with this
  25.  * quantizer, though you can turn it off if you really want to.
  26.  *
  27.  * In 1-pass quantization the colormap must be chosen in advance of seeing the
  28.  * image.  We use a map consisting of all combinations of Ncolors[i] color
  29.  * values for the i'th component.  The Ncolors[] values are chosen so that
  30.  * their product, the total number of colors, is no more than that requested.
  31.  * (In most cases, the product will be somewhat less.)
  32.  *
  33.  * Since the colormap is orthogonal, the representative value for each color
  34.  * component can be determined without considering the other components;
  35.  * then these indexes can be combined into a colormap index by a standard
  36.  * N-dimensional-array-subscript calculation.  Most of the arithmetic involved
  37.  * can be precalculated and stored in the lookup table colorindex[].
  38.  * colorindex[i][j] maps pixel value j in component i to the nearest
  39.  * representative value (grid plane) for that component; this index is
  40.  * multiplied by the array stride for component i, so that the
  41.  * index of the colormap entry closest to a given pixel value is just
  42.  *    sum( colorindex[component-number][pixel-component-value] )
  43.  * Aside from being fast, this scheme allows for variable spacing between
  44.  * representative values with no additional lookup cost.
  45.  *
  46.  * If gamma correction has been applied in color conversion, it might be wise
  47.  * to adjust the color grid spacing so that the representative colors are
  48.  * equidistant in linear space.  At this writing, gamma correction is not
  49.  * implemented by jdcolor, so nothing is done here.
  50.  */
  51.  
  52.  
  53. /* Declarations for ordered dithering.
  54.  *
  55.  * We use a standard 4x4 ordered dither array.  The basic concept of ordered
  56.  * dithering is described in many references, for instance Dale Schumacher's
  57.  * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  58.  * In place of Schumacher's comparisons against a "threshold" value, we add a
  59.  * "dither" value to the input pixel and then round the result to the nearest
  60.  * output value.  The dither value is equivalent to (0.5 - threshold) times
  61.  * the distance between output values.  For ordered dithering, we assume that
  62.  * the output colors are equally spaced; if not, results will probably be
  63.  * worse, since the dither may be too much or too little at a given point.
  64.  *
  65.  * The normal calculation would be to form pixel value + dither, range-limit
  66.  * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  67.  * We can skip the separate range-limiting step by extending the colorindex
  68.  * table in both directions.
  69.  */
  70.  
  71. #define ODITHER_SIZE  4        /* dimension of dither matrix */
  72. #define ODITHER_CELLS (4*4)    /* number of cells in dither matrix */
  73. #define ODITHER_MASK  3        /* mask for wrapping around dither counters */
  74.  
  75. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  76.  
  77.  
  78. /* Declarations for Floyd-Steinberg dithering.
  79.  *
  80.  * Errors are accumulated into the array fserrors[], at a resolution of
  81.  * 1/16th of a pixel count.  The error at a given pixel is propagated
  82.  * to its not-yet-processed neighbors using the standard F-S fractions,
  83.  *        ...    (here)    7/16
  84.  *        3/16    5/16    1/16
  85.  * We work left-to-right on even rows, right-to-left on odd rows.
  86.  *
  87.  * We can get away with a single array (holding one row's worth of errors)
  88.  * by using it to store the current row's errors at pixel columns not yet
  89.  * processed, but the next row's errors at columns already processed.  We
  90.  * need only a few extra variables to hold the errors immediately around the
  91.  * current column.  (If we are lucky, those variables are in registers, but
  92.  * even if not, they're probably cheaper to access than array elements are.)
  93.  *
  94.  * The fserrors[] array is indexed [component#][position].
  95.  * We provide (#columns + 2) entries per component; the extra entry at each
  96.  * end saves us from special-casing the first and last pixels.
  97.  *
  98.  * Note: on a wide image, we might not have enough room in a PC's near data
  99.  * segment to hold the error array; so it is allocated with alloc_large.
  100.  */
  101.  
  102. #if BITS_IN_JSAMPLE == 8
  103. typedef INT16 FSERROR;        /* 16 bits should be enough */
  104. typedef int LOCFSERROR;        /* use 'int' for calculation temps */
  105. #else
  106. typedef INT32 FSERROR;        /* may need more than 16 bits */
  107. typedef INT32 LOCFSERROR;    /* be sure calculation temps are big enough */
  108. #endif
  109.  
  110. typedef FSERROR FAR *FSERRPTR;    /* pointer to error array (in FAR storage!) */
  111.  
  112.  
  113. /* Private subobject */
  114.  
  115. #define MAX_Q_COMPS 4        /* max components I can handle */
  116.  
  117. typedef struct {
  118.   struct jpeg_color_quantizer pub; /* public fields */
  119.  
  120.   JSAMPARRAY colorindex;    /* Precomputed mapping for speed */
  121.   /* colorindex[i][j] = index of color closest to pixel value j in component i,
  122.    * premultiplied as described above.  Since colormap indexes must fit into
  123.    * JSAMPLEs, the entries of this array will too.
  124.    */
  125.  
  126.   /* Variables for ordered dithering */
  127.   int row_index;        /* cur row's vertical index in dither matrix */
  128.   ODITHER_MATRIX *odither;    /* one dither array per component */
  129.  
  130.   /* Variables for Floyd-Steinberg dithering */
  131.   FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  132.   boolean on_odd_row;        /* flag to remember which row we are on */
  133. } my_cquantizer;
  134.  
  135. typedef my_cquantizer * my_cquantize_ptr;
  136.  
  137.  
  138. /*
  139.  * Policy-making subroutines for create_colormap: these routines determine
  140.  * the colormap to be used.  The rest of the module only assumes that the
  141.  * colormap is orthogonal.
  142.  *
  143.  *  * select_ncolors decides how to divvy up the available colors
  144.  *    among the components.
  145.  *  * output_value defines the set of representative values for a component.
  146.  *  * largest_input_value defines the mapping from input values to
  147.  *    representative values for a component.
  148.  * Note that the latter two routines may impose different policies for
  149.  * different components, though this is not currently done.
  150.  */
  151.  
  152.  
  153. LOCAL int
  154. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  155. /* Determine allocation of desired colors to components, */
  156. /* and fill in Ncolors[] array to indicate choice. */
  157. /* Return value is total number of colors (product of Ncolors[] values). */
  158. {
  159.   int nc = cinfo->out_color_components; /* number of color components */
  160.   int max_colors = cinfo->desired_number_of_colors;
  161.   int total_colors, iroot, i, j;
  162.   long temp;
  163.   static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  164.  
  165.   /* We can allocate at least the nc'th root of max_colors per component. */
  166.   /* Compute floor(nc'th root of max_colors). */
  167.   iroot = 1;
  168.   do {
  169.     iroot++;
  170.     temp = iroot;        /* set temp = iroot ** nc */
  171.     for (i = 1; i < nc; i++)
  172.       temp *= iroot;
  173.   } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  174.   iroot--;            /* now iroot = floor(root) */
  175.  
  176.   /* Must have at least 2 color values per component */
  177.   if (iroot < 2)
  178.     ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  179.  
  180.   /* Initialize to iroot color values for each component */
  181.   total_colors = 1;
  182.   for (i = 0; i < nc; i++) {
  183.     Ncolors[i] = iroot;
  184.     total_colors *= iroot;
  185.   }
  186.   /* We may be able to increment the count for one or more components without
  187.    * exceeding max_colors, though we know not all can be incremented.
  188.    * In RGB colorspace, try to increment G first, then R, then B.
  189.    */
  190.   for (i = 0; i < nc; i++) {
  191.     j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  192.     /* calculate new total_colors if Ncolors[j] is incremented */
  193.     temp = total_colors / Ncolors[j];
  194.     temp *= Ncolors[j]+1;    /* done in long arith to avoid oflo */
  195.     if (temp > (long) max_colors)
  196.       break;            /* won't fit, done */
  197.     Ncolors[j]++;        /* OK, apply the increment */
  198.     total_colors = (int) temp;
  199.   }
  200.  
  201.   return total_colors;
  202. }
  203.  
  204.  
  205. LOCAL int
  206. output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  207. /* Return j'th output value, where j will range from 0 to maxj */
  208. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  209. {
  210.   /* We always provide values 0 and MAXJSAMPLE for each component;
  211.    * any additional values are equally spaced between these limits.
  212.    * (Forcing the upper and lower values to the limits ensures that
  213.    * dithering can't produce a color outside the selected gamut.)
  214.    */
  215.   return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  216. }
  217.  
  218.  
  219. LOCAL int
  220. largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  221. /* Return largest input value that should map to j'th output value */
  222. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  223. {
  224.   /* Breakpoints are halfway between values returned by output_value */
  225.   return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  226. }
  227.  
  228.  
  229. /*
  230.  * Create the colormap and color index table.
  231.  * Also creates the ordered-dither tables, if required.
  232.  */
  233.  
  234. LOCAL void
  235. create_colormap (j_decompress_ptr cinfo)
  236. {
  237.   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  238.   JSAMPARRAY colormap;        /* Created colormap */
  239.   JSAMPROW indexptr;
  240.   int total_colors;        /* Number of distinct output colors */
  241.   int Ncolors[MAX_Q_COMPS];    /* # of values alloced to each component */
  242.   ODITHER_MATRIX *odither;
  243.   int i,j,k, nci, blksize, blkdist, ptr, val, pad;
  244.  
  245.   /* Select number of colors for each component */
  246.   total_colors = select_ncolors(cinfo, Ncolors);
  247.  
  248.   /* Report selected color counts */
  249.   if (cinfo->out_color_components == 3)
  250.     TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  251.          total_colors, Ncolors[0], Ncolors[1], Ncolors[2]);
  252.   else
  253.     TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  254.  
  255.   /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  256.    * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  257.    * This is not necessary in the other dithering modes.
  258.    */
  259.   pad = (cinfo->dither_mode == JDITHER_ORDERED) ? MAXJSAMPLE*2 : 0;
  260.  
  261.   /* Allocate and fill in the colormap and color index. */
  262.   /* The colors are ordered in the map in standard row-major order, */
  263.   /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  264.  
  265.   colormap = (*cinfo->mem->alloc_sarray)
  266.     ((j_common_ptr) cinfo, JPOOL_IMAGE,
  267.      (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  268.   cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  269.     ((j_common_ptr) cinfo, JPOOL_IMAGE,
  270.      (JDIMENSION) (MAXJSAMPLE+1 + pad),
  271.      (JDIMENSION) cinfo->out_color_components);
  272.  
  273.   /* blksize is number of adjacent repeated entries for a component */
  274.   /* blkdist is distance between groups of identical entries for a component */
  275.   blkdist = total_colors;
  276.  
  277.   for (i = 0; i < cinfo->out_color_components; i++) {
  278.     /* fill in colormap entries for i'th color component */
  279.     nci = Ncolors[i];        /* # of distinct values for this color */
  280.     blksize = blkdist / nci;
  281.     for (j = 0; j < nci; j++) {
  282.       /* Compute j'th output value (out of nci) for component */
  283.       val = output_value(cinfo, i, j, nci-1);
  284.       /* Fill in all colormap entries that have this value of this component */
  285.       for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  286.     /* fill in blksize entries beginning at ptr */
  287.     for (k = 0; k < blksize; k++)
  288.       colormap[i][ptr+k] = (JSAMPLE) val;
  289.       }
  290.     }
  291.     blkdist = blksize;        /* blksize of this color is blkdist of next */
  292.  
  293.     /* adjust colorindex pointers to provide padding at negative indexes. */
  294.     if (pad)
  295.       cquantize->colorindex[i] += MAXJSAMPLE;
  296.  
  297.     /* fill in colorindex entries for i'th color component */
  298.     /* in loop, val = index of current output value, */
  299.     /* and k = largest j that maps to current val */
  300.     indexptr = cquantize->colorindex[i];
  301.     val = 0;
  302.     k = largest_input_value(cinfo, i, 0, nci-1);
  303.     for (j = 0; j <= MAXJSAMPLE; j++) {
  304.       while (j > k)        /* advance val if past boundary */
  305.     k = largest_input_value(cinfo, i, ++val, nci-1);
  306.       /* premultiply so that no multiplication needed in main processing */
  307.       indexptr[j] = (JSAMPLE) (val * blksize);
  308.     }
  309.     /* Pad at both ends if necessary */
  310.     if (pad)
  311.       for (j = 1; j <= MAXJSAMPLE; j++) {
  312.     indexptr[-j] = indexptr[0];
  313.     indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  314.       }
  315.   }
  316.  
  317.   /* Make the colormap available to the application. */
  318.   cinfo->colormap = colormap;
  319.   cinfo->actual_number_of_colors = total_colors;
  320.  
  321.   if (cinfo->dither_mode == JDITHER_ORDERED) {
  322.     /* Allocate and fill in the ordered-dither tables. */
  323.     odither = (ODITHER_MATRIX *)
  324.       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  325.             cinfo->out_color_components * SIZEOF(ODITHER_MATRIX));
  326.     cquantize->odither = odither;
  327.     for (i = 0; i < cinfo->out_color_components; i++) {
  328.       nci = Ncolors[i];        /* # of distinct values for this color */
  329.       /* The inter-value distance for this color is MAXJSAMPLE/(nci-1).
  330.        * Hence the dither value for the matrix cell with fill order j
  331.        * (j=1..N) should be (N+1-2*j)/(2*(N+1)) * MAXJSAMPLE/(nci-1).
  332.        */
  333.       val = 2 * (ODITHER_CELLS + 1) * (nci - 1); /* denominator */
  334.       /* Macro is coded to ensure round towards zero despite C's
  335.        * lack of consistency in integer division...
  336.        */
  337. #define ODITHER_DIV(num,den)  ((num)<0 ? -((-(num))/(den)) : (num)/(den))
  338. #define ODITHER_VAL(j)  ODITHER_DIV((ODITHER_CELLS+1-2*j)*MAXJSAMPLE, val)
  339.       /* Traditional fill order for 4x4 dither; see Schumacher's figure 4. */
  340.       odither[0][0][0] = ODITHER_VAL(1);
  341.       odither[0][0][1] = ODITHER_VAL(9);
  342.       odither[0][0][2] = ODITHER_VAL(3);
  343.       odither[0][0][3] = ODITHER_VAL(11);
  344.       odither[0][1][0] = ODITHER_VAL(13);
  345.       odither[0][1][1] = ODITHER_VAL(5);
  346.       odither[0][1][2] = ODITHER_VAL(15);
  347.       odither[0][1][3] = ODITHER_VAL(7);
  348.       odither[0][2][0] = ODITHER_VAL(4);
  349.       odither[0][2][1] = ODITHER_VAL(12);
  350.       odither[0][2][2] = ODITHER_VAL(2);
  351.       odither[0][2][3] = ODITHER_VAL(10);
  352.       odither[0][3][0] = ODITHER_VAL(16);
  353.       odither[0][3][1] = ODITHER_VAL(8);
  354.       odither[0][3][2] = ODITHER_VAL(14);
  355.       odither[0][3][3] = ODITHER_VAL(6);
  356.       odither++;        /* advance to next matrix */
  357.     }
  358.   }
  359. }
  360.  
  361.  
  362. /*
  363.  * Map some rows of pixels to the output colormapped representation.
  364.  */
  365.  
  366. METHODDEF void
  367. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  368.         JSAMPARRAY output_buf, int num_rows)
  369. /* General case, no dithering */
  370. {
  371.   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  372.   JSAMPARRAY colorindex = cquantize->colorindex;
  373.   register int pixcode, ci;
  374.   register JSAMPROW ptrin, ptrout;
  375.   int row;
  376.   JDIMENSION col;
  377.   JDIMENSION width = cinfo->output_width;
  378.   register int nc = cinfo->out_color_components;
  379.  
  380.   for (row = 0; row < num_rows; row++) {
  381.     ptrin = input_buf[row];
  382.     ptrout = output_buf[row];
  383.     for (col = width; col > 0; col--) {
  384.       pixcode = 0;
  385.       for (ci = 0; ci < nc; ci++) {
  386.     pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  387.       }
  388.       *ptrout++ = (JSAMPLE) pixcode;
  389.     }
  390.   }
  391. }
  392.  
  393.  
  394. METHODDEF void
  395. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  396.          JSAMPARRAY output_buf, int num_rows)
  397. /* Fast path for out_color_components==3, no dithering */
  398. {
  399.   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  400.   register int pixcode;
  401.   register JSAMPROW ptrin, ptrout;
  402.   JSAMPROW colorindex0 = cquantize->colorindex[0];
  403.   JSAMPROW colorindex1 = cquantize->colorindex[1];
  404.   JSAMPROW colorindex2 = cquantize->colorindex[2];
  405.   int row;
  406.   JDIMENSION col;
  407.   JDIMENSION width = cinfo->output_width;
  408.  
  409.   for (row = 0; row < num_rows; row++) {
  410.     ptrin = input_buf[row];
  411.     ptrout = output_buf[row];
  412.     for (col = width; col > 0; col--) {
  413.       pixcode  = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  414.       pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  415.       pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  416.       *ptrout++ = (JSAMPLE) pixcode;
  417.     }
  418.   }
  419. }
  420.  
  421.  
  422. METHODDEF void
  423. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  424.              JSAMPARRAY output_buf, int num_rows)
  425. /* General case, with ordered dithering */
  426. {
  427.   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  428.   register JSAMPROW input_ptr;
  429.   register JSAMPROW output_ptr;
  430.   JSAMPROW colorindex_ci;
  431.   int * dither;            /* points to active row of dither matrix */
  432.   int row_index, col_index;    /* current indexes into dither matrix */
  433.   int nc = cinfo->out_color_components;
  434.   int ci;
  435.   int row;
  436.   JDIMENSION col;
  437.   JDIMENSION width = cinfo->output_width;
  438.  
  439.   for (row = 0; row < num_rows; row++) {
  440.     /* Initialize output values to 0 so can process components separately */
  441.     jzero_far((void FAR *) output_buf[row],
  442.           (size_t) (width * SIZEOF(JSAMPLE)));
  443.     row_index = cquantize->row_index;
  444.     for (ci = 0; ci < nc; ci++) {
  445.       input_ptr = input_buf[row] + ci;
  446.       output_ptr = output_buf[row];
  447.       colorindex_ci = cquantize->colorindex[ci];
  448.       dither = cquantize->odither[ci][row_index];
  449.       col_index = 0;
  450.  
  451.       for (col = width; col > 0; col--) {
  452.     /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  453.      * select output value, accumulate into output code for this pixel.
  454.      * Range-limiting need not be done explicitly, as we have extended
  455.      * the colorindex table to produce the right answers for out-of-range
  456.      * inputs.  The maximum dither is +- MAXJSAMPLE; this sets the
  457.      * required amount of padding.
  458.      */
  459.     *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  460.     input_ptr += nc;
  461.     output_ptr++;
  462.     col_index = (col_index + 1) & ODITHER_MASK;
  463.       }
  464.     }
  465.     /* Advance row index for next row */
  466.     row_index = (row_index + 1) & ODITHER_MASK;
  467.     cquantize->row_index = row_index;
  468.   }
  469. }
  470.  
  471.  
  472. METHODDEF void
  473. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  474.               JSAMPARRAY output_buf, int num_rows)
  475. /* Fast path for out_color_components==3, with ordered dithering */
  476. {
  477.   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  478.   register int pixcode;
  479.   register JSAMPROW input_ptr;
  480.   register JSAMPROW output_ptr;
  481.   JSAMPROW colorindex0 = cquantize->colorindex[0];
  482.   JSAMPROW colorindex1 = cquantize->colorindex[1];
  483.   JSAMPROW colorindex2 = cquantize->colorindex[2];
  484.   int * dither0;        /* points to active row of dither matrix */
  485.   int * dither1;
  486.   int * dither2;
  487.   int row_index, col_index;    /* current indexes into dither matrix */
  488.   int row;
  489.   JDIMENSION col;
  490.   JDIMENSION width = cinfo->output_width;
  491.  
  492.   for (row = 0; row < num_rows; row++) {
  493.     row_index = cquantize->row_index;
  494.     input_ptr = input_buf[row];
  495.     output_ptr = output_buf[row];
  496.     dither0 = cquantize->odither[0][row_index];
  497.     dither1 = cquantize->odither[1][row_index];
  498.     dither2 = cquantize->odither[2][row_index];
  499.     col_index = 0;
  500.  
  501.     for (col = width; col > 0; col--) {
  502.       pixcode  = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  503.                     dither0[col_index]]);
  504.       pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  505.                     dither1[col_index]]);
  506.       pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  507.                     dither2[col_index]]);
  508.       *output_ptr++ = (JSAMPLE) pixcode;
  509.       col_index = (col_index + 1) & ODITHER_MASK;
  510.     }
  511.     row_index = (row_index + 1) & ODITHER_MASK;
  512.     cquantize->row_index = row_index;
  513.   }
  514. }
  515.  
  516.  
  517. METHODDEF void
  518. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  519.             JSAMPARRAY output_buf, int num_rows)
  520. /* General case, with Floyd-Steinberg dithering */
  521. {
  522.   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  523.   register LOCFSERROR cur;    /* current error or pixel value */
  524.   LOCFSERROR belowerr;        /* error for pixel below cur */
  525.   LOCFSERROR bpreverr;        /* error for below/prev col */
  526.   LOCFSERROR bnexterr;        /* error for below/next col */
  527.   LOCFSERROR delta;
  528.   register FSERRPTR errorptr;    /* => fserrors[] at column before current */
  529.   register JSAMPROW input_ptr;
  530.   register JSAMPROW output_ptr;
  531.   JSAMPROW colorindex_ci;
  532.   JSAMPROW colormap_ci;
  533.   int pixcode;
  534.   int nc = cinfo->out_color_components;
  535.   int dir;            /* 1 for left-to-right, -1 for right-to-left */
  536.   int dirnc;            /* dir * nc */
  537.   int ci;
  538.   int row;
  539.   JDIMENSION col;
  540.   JDIMENSION width = cinfo->output_width;
  541.   JSAMPLE *range_limit = cinfo->sample_range_limit;
  542.   SHIFT_TEMPS
  543.  
  544.   for (row = 0; row < num_rows; row++) {
  545.     /* Initialize output values to 0 so can process components separately */
  546.     jzero_far((void FAR *) output_buf[row],
  547.           (size_t) (width * SIZEOF(JSAMPLE)));
  548.     for (ci = 0; ci < nc; ci++) {
  549.       input_ptr = input_buf[row] + ci;
  550.       output_ptr = output_buf[row];
  551.       if (cquantize->on_odd_row) {
  552.     /* work right to left in this row */
  553.     input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  554.     output_ptr += width-1;
  555.     dir = -1;
  556.     dirnc = -nc;
  557.     errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  558.       } else {
  559.     /* work left to right in this row */
  560.     dir = 1;
  561.     dirnc = nc;
  562.     errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  563.       }
  564.       colorindex_ci = cquantize->colorindex[ci];
  565.       colormap_ci = cinfo->colormap[ci];
  566.       /* Preset error values: no error propagated to first pixel from left */
  567.       cur = 0;
  568.       /* and no error propagated to row below yet */
  569.       belowerr = bpreverr = 0;
  570.  
  571.       for (col = width; col > 0; col--) {
  572.     /* cur holds the error propagated from the previous pixel on the
  573.      * current line.  Add the error propagated from the previous line
  574.      * to form the complete error correction term for this pixel, and
  575.      * round the error term (which is expressed * 16) to an integer.
  576.      * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  577.      * for either sign of the error value.
  578.      * Note: errorptr points to *previous* column's array entry.
  579.      */
  580.     cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  581.     /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  582.      * The maximum error is +- MAXJSAMPLE; this sets the required size
  583.      * of the range_limit array.
  584.      */
  585.     cur += GETJSAMPLE(*input_ptr);
  586.     cur = GETJSAMPLE(range_limit[cur]);
  587.     /* Select output value, accumulate into output code for this pixel */
  588.     pixcode = GETJSAMPLE(colorindex_ci[cur]);
  589.     *output_ptr += (JSAMPLE) pixcode;
  590.     /* Compute actual representation error at this pixel */
  591.     /* Note: we can do this even though we don't have the final */
  592.     /* pixel code, because the colormap is orthogonal. */
  593.     cur -= GETJSAMPLE(colormap_ci[pixcode]);
  594.     /* Compute error fractions to be propagated to adjacent pixels.
  595.      * Add these into the running sums, and simultaneously shift the
  596.      * next-line error sums left by 1 column.
  597.      */
  598.     bnexterr = cur;
  599.     delta = cur * 2;
  600.     cur += delta;        /* form error * 3 */
  601.     errorptr[0] = (FSERROR) (bpreverr + cur);
  602.     cur += delta;        /* form error * 5 */
  603.     bpreverr = belowerr + cur;
  604.     belowerr = bnexterr;
  605.     cur += delta;        /* form error * 7 */
  606.     /* At this point cur contains the 7/16 error value to be propagated
  607.      * to the next pixel on the current line, and all the errors for the
  608.      * next line have been shifted over. We are therefore ready to move on.
  609.      */
  610.     input_ptr += dirnc;    /* advance input ptr to next column */
  611.     output_ptr += dir;    /* advance output ptr to next column */
  612.     errorptr += dir;    /* advance errorptr to current column */
  613.       }
  614.       /* Post-loop cleanup: we must unload the final error value into the
  615.        * final fserrors[] entry.  Note we need not unload belowerr because
  616.        * it is for the dummy column before or after the actual array.
  617.        */
  618.       errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  619.     }
  620.     cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  621.   }
  622. }
  623.  
  624.  
  625. /*
  626.  * Initialize for one-pass color quantization.
  627.  */
  628.  
  629. METHODDEF void
  630. start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  631. {
  632.   /* no work in 1-pass case */
  633. }
  634.  
  635.  
  636. /*
  637.  * Finish up at the end of the pass.
  638.  */
  639.  
  640. METHODDEF void
  641. finish_pass_1_quant (j_decompress_ptr cinfo)
  642. {
  643.   /* no work in 1-pass case */
  644. }
  645.  
  646.  
  647. /*
  648.  * Module initialization routine for 1-pass color quantization.
  649.  */
  650.  
  651. GLOBAL void
  652. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  653. {
  654.   my_cquantize_ptr cquantize;
  655.   size_t arraysize;
  656.   int i;
  657.  
  658.   cquantize = (my_cquantize_ptr)
  659.     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  660.                 SIZEOF(my_cquantizer));
  661.   cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  662.   cquantize->pub.start_pass = start_pass_1_quant;
  663.   cquantize->pub.finish_pass = finish_pass_1_quant;
  664.  
  665.   /* Make sure my internal arrays won't overflow */
  666.   if (cinfo->out_color_components > MAX_Q_COMPS)
  667.     ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  668.   /* Make sure colormap indexes can be represented by JSAMPLEs */
  669.   if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  670.     ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  671.  
  672.   /* Initialize for desired dithering mode. */
  673.   switch (cinfo->dither_mode) {
  674.   case JDITHER_NONE:
  675.     if (cinfo->out_color_components == 3)
  676.       cquantize->pub.color_quantize = color_quantize3;
  677.     else
  678.       cquantize->pub.color_quantize = color_quantize;
  679.     break;
  680.   case JDITHER_ORDERED:
  681.     if (cinfo->out_color_components == 3)
  682.       cquantize->pub.color_quantize = quantize3_ord_dither;
  683.     else
  684.       cquantize->pub.color_quantize = quantize_ord_dither;
  685.     cquantize->row_index = 0;    /* initialize state for ordered dither */
  686.     break;
  687.   case JDITHER_FS:
  688.     cquantize->pub.color_quantize = quantize_fs_dither;
  689.     cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  690.     /* Allocate Floyd-Steinberg workspace if necessary. */
  691.     /* We do this now since it is FAR storage and may affect the memory */
  692.     /* manager's space calculations. */
  693.     arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  694.     for (i = 0; i < cinfo->out_color_components; i++) {
  695.       cquantize->fserrors[i] = (FSERRPTR) (*cinfo->mem->alloc_large)
  696.     ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  697.       /* Initialize the propagated errors to zero. */
  698.       jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  699.     }
  700.     break;
  701.   default:
  702.     ERREXIT(cinfo, JERR_NOT_COMPILED);
  703.     break;
  704.   }
  705.  
  706.   /* Create the colormap. */
  707.   create_colormap(cinfo);
  708. }
  709.  
  710. #endif /* QUANT_1PASS_SUPPORTED */
  711.